﻿using SvgViewer.Entities;
using System;
using System.IO;
using System.Text;
using System.Windows.Media;
using SvgViewer.Core;

namespace SvgViewer.ViewModel;

/// <summary>
/// 明细视图 ViewModel
/// </summary>
public class DetailViewModel : ViewModelBase
{
    private SvgInfo info;

    /// <summary>
    /// 构造
    /// </summary>
    /// <param name="info">Svg信息</param>
    public DetailViewModel(SvgInfo info)
    {
        this.info = info;
        ContentRenderedCommand = new RelayCommand(_ => {
            LoadContent();
        });
    }

#region Properties...

    /// <summary>
    /// SVG图像文件路径
    /// </summary>
    public string FilePath => info.FilePath;

    /// <summary>
    /// 第一次呈现内容后触发
    /// </summary>
    public RelayCommand ContentRenderedCommand { get; }

    /// <summary>
    /// Svg 内容
    /// </summary>
    public string Svg {
        get;
        private set;
    }

    /// <summary>
    /// Xaml 内容
    /// </summary>
    public string Xaml {
        get;
        private set;
    }

    /// <summary>
    /// 图像源
    /// </summary>
    public ImageSource ImageSource => info.ImageSource;

#endregion

    private void LoadContent()
    {
        try
        {
            using (var fs = new FileStream(FilePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                using (var sr = new StreamReader(fs, Encoding.UTF8))
                {
                    Svg = sr.ReadToEnd();
                }
            }

            Xaml  = info.Content;
        }
        catch (Exception ex)
        {
            Xaml = ex.Message;
        }

        this.OnPropertyChanged(string.Empty);
    }
}